
Ext.define('Sencha.controller.PhraseListController', {
    extend: 'Ext.app.Controller',

    config: {
           
           catData : [
                      {
                      
                      text: 'Conversation',
                      id: '1',
                      iconURL: 'images/Conversations.png',
                      items: [
                              {
                              id: '21',
                              text: 'Basic',
                              leaf: true
                              }, 
                              {
                              id: '22',
                              text: 'Questions',
                              leaf: true
                              },
                              {
                              id: '23',
                              text: 'Meeting People',
                              leaf: true
                              },
                              {
                              id: '24',
                              text: 'Feelings and Qualities',
                              leaf: true
                              }
                              ]
                      },
                      {
                      text: 'Language',
                      leaf: true,
                      id: '2',
                      iconURL: 'images/Language.png'
                      },
                      {
                      text: 'Relationships',
                      id: '3',
                      iconURL: 'images/Relationships.png',
                      items: [
                              {
                              id: '29',
                              text: 'Family Terms',
                              leaf: true
                              },
                              {
                              id: '30',
                              text: 'Marital Status And Children',
                              leaf: true
                              },
                              {
                              id: '31',
                              text: 'Love And Jealousy',
                              leaf: true
                              }
                              ]
                      },
                      {
                      text: 'Weather and Seasons',
                      id: '4',
                      iconURL: 'images/WeatherAndSeasons.png',
                      items: [
                              {
                              id: '32',
                              text: 'Weather and Tides',
                              leaf: true
                              },
                              {
                              id: '33',
                              text: 'Seasons',
                              leaf: true
                              },
                              {
                              id: '34',
                              text: 'Signs Of The Seasons',
                              leaf: true
                              }
                              ]
                      },
                      {
                      text: 'Time',
                      leaf: true,
                      id: '5',
                      iconURL: 'images/Time.png'
                      },
                      {
                      text: 'The Arts',
                      id: '6',
                      iconURL: 'images/TheArts.png',
                      items: [
                              {
                              id: '35',
                              text: 'Music and Dance',
                              leaf: true
                              },
                              {
                              id: '36',
                              text: 'Painting And Craft',
                              leaf: true
                              }
                              ]
                      },
                      {
                      text: 'Health and the Body',
                      leaf: true,
                      id: '7',
                      iconURL: 'images/HealthAndTheBody.png'
                      },
                      {
                      text: 'Law',
                      leaf: true,
                      id: '8',
                      iconURL: 'images/Law.png'
                      },
                      {
                      text: 'Land and Sea',
                      id: '9',
                      iconURL: 'images/LandAndSea.png',
                      items: [
                              {
                              id: '37',
                              text: 'Going On Country',
                              leaf: true
                              },
                              {
                              id: '38',
                              text: 'Geographical Terms',
                              leaf: true
                              },
                              {
                              id: '39',
                              text: 'Marine Terms',
                              leaf: true
                              },
                              ]
                      },
                      {
                      text: 'Money',
                      leaf: true,
                      id: '10',
                      iconURL: 'images/Money.png'
                      },
                      {
                      text: 'Numbers and Quantity',
                      leaf: true,
                      id: '11',
                      iconURL: 'images/NumbersAndQuantity.png'
                      },
                      {
                      text: 'Cooking and Eating',
                      id: '12',
                      iconURL: 'images/CookingAndEating.png',
                      items: [
                              {
                              id: '25',
                              text: 'Cooking',
                              leaf: true
                              },
                              {
                              id: '26',
                              text: 'Eating',
                              leaf: true
                              },
                              ]
                      },
                      {
                      text: 'Hunting and Gathering',
                      id: '13',
                      iconURL: 'images/HuntingAndGathering.png',
                      items: [
                              {
                              id: '27',
                              text: 'On The Coast',
                              leaf: true
                              },
                              {
                              id: '28',
                              text: 'Inland',
                              leaf: true
                              },
                              ]
                      },
                      {
                      text: 'Going Places',
                      id: '14',
                      iconURL: 'images/GoingPlaces.png',
                      items: [
                              {
                              id: '16',
                              text: 'Coming and Going',
                              leaf: true
                              },
                              {
                              id: '17',
                              text: 'Going by Road',
                              leaf: true
                              },
                              
                              {
                              id: '18',
                              text: 'Going by Air',
                              leaf: true
                              },
                              {
                              id: '19',
                              text: 'Going by Sea',
                              leaf: true
                              },
                              {
                              id: '20',
                              text: 'Directions',
                              leaf: true
                              }
                              ]
                      },
                      {
                      text: 'My Phrases',
                      id: '15',
                      iconURL: 'images/MyPhrases.png',
                      leaf: true
                      }
                      ],

           
        // Flags used to check state of search filter buttons
        //engPhraseButtonOn: false,
        //iwaPhraseButtonOn: true,
         
        // Dictionary Target & Source property
        sourcePhrasefield : "",
        targetPhraseField : "",
        orthographyField : "",
        audioUrlField: "",
        noteField : "",
        //metadata form
        currentDate: "",
        //currentTime: "",
        currentLatitude: "",
        currentLongitude: "",
        recordingDevice: "",
        //speaker form
        speakerName: "",
        speakerDOB: "",
        speakerGender: "",
        speakerComment: "",
        //collector form
        collectorName: "",
        collectorDOB: "",
        collectorGender: "",
        collectorComment: "",
        //id's
        collectorId: "",
        speakerId: "",
           
        categoryTapped: null,
        phraseTapped: null,
        lastSearchString: '',
           
        // constants
        myPhrasesCategoryId: '15',
           
        refs: {
           main: 'phrasenavigationview',
           phraseCategoriesListView: 'phrasecategorieslistview',
           phraseParentCategoryListview: 'phraseparentcategorylistview',
           phraseChildCategoryListview: 'phrasechildcategorylistview',
           phraseListView: 'phraselistview',
           phraseForm: 'fieldset[id=phraseFormFieldSet]',
           //phraseEntryButton: 'button[id=phraseEntryButton]',
           phraseToolbarButton: 'button[cls=phraseEntryButton]',
           //dictionaryDeleteButton: 'button[id=deleteDictionaryButton]',
           phraseSearchField: 'searchfield[name=phraseSearchField]',
           //dictionarySourceListView: 'dictionarysourcelistview',
      
           phraseDeleteButton: 'button[id=deletePhraseButton]',
           dicMetadaForm: 'fieldset[id="dicMetadataFieldset"]'
           
           //engPhraseButton: 'button[id=engPhraseButtonId]',
           //iwaPhraseButton: 'button[id=iwaPhraseButtonId]'
           //addImageButtonRef: 'button[cls=addImageButtonCls]',
           //audioRecordButtonRef: 'button[cls=audioRecordButtonCls]',
           
        },
        
     
        control: {
           main: {
                back: 'onBackButton'
           },
            phraseSearchField:{        
                keyup:'filterPhraseSearch',
                clearicontap:'clearPhraseSearchFilter'
            },
            phraseToolbarButton: {
                tap: 'onPhraseToolbarButtonTapped'
            },
           phraseListView: {
                activate: 'onPhraseListActivated',
                itemtap: 'onPhraseItemTap'
           },
           phraseChildCategoryListview: {
                itemtap: 'onChildCategoryItemTap'
           },
           'button[id="phraseMetadataButton"]': {
                tap:'showMetadataForm'
           },
           'button[id="deletePhraseButton"]': {
                tap:'deletePhraseEntry'
           }

            /*,
            'engPhraseButton' :{
           		tap: 'toggleEngPhraseButton'
                //show: 'showDictionaryAddButton'
            },
            'iwaPhraseButton' :{
           		tap: 'toggleIwaPhraseButton'
            },
            'dictionarysourcenavigationview':{
            	back:'onBackButton'
           },*/
        }
    },
    
           
    // Setup event handlers here because Sencha bug? doesn't 
    // detect show, activate or painted
    //
    launch: function() { 
        this.getPhraseParentCategoryListview().on({
            painted : { fn: this.onPhraseParentCategoryPainted, scope: this },
            itemtap: { fn: this.onParentCategoryItemTap, scope: this }
        });      
    },
      
           
    // Set data for top level phrase categories list
    //
    onPhraseParentCategoryPainted: function() {
        this.getPhraseParentCategoryListview().setData( this.getCatData() );
    },
           
      
    // show phrase list (called when phrase sub category list item tapped)
    //
    onChildCategoryItemTap: function(view,index,htmlElement,e,opts) {
        // Sencha bug allows the disclosure arrow to be clicked more than once, so check for this
        var innerItems = this.getMain().getInnerItems();
        if ( innerItems.length > 2 ) {
           return;
        }
           
        var tappedCat = this.getPhraseChildCategoryListview().getData()[index];
        var tappedCatId = tappedCat.id;
           
        this.setCategoryTapped(tappedCatId);
        this.getMain().push({xtype: 'phrasecontainerlist', title: tappedCat.text});
    },
           
           
    // show phrase list or phrase sub categores (called when phrase category list item tapped)
    //
    onParentCategoryItemTap: function(view,index,htmlElement,e,opts) {
        // Sencha bug allows the disclosure arrow to be clicked more than once, so check for this
        var innerItems = this.getMain().getInnerItems();
        if ( innerItems.length > 1 ) {
           return;
        }
           
        console.log('innterItems = ' + innerItems);
           
        var tappedCat = this.getCatData()[index];
        var tappedCatId = tappedCat.id;
           
        if ( tappedCat.leaf ) {
           // show phrases
           this.setCategoryTapped(tappedCatId);
           this.getMain().push({xtype: 'phrasecontainerlist', title: tappedCat.text});
        } else {
            // show sub category list
            this.getMain().push({xtype: 'phrasechildcategorylistview', title: tappedCat.text, data: tappedCat.items});
        }
    },
           
    // Expand list row to display orthography and targe phrase and play audio
    //     
    onPhraseItemTap: function(view,index,htmlElement,e,opts) {
        this.setPhraseTapped(index); // remember index for later
        
        // If in custom phrases category, change button text to 'edit'
        if ( this.getCategoryTapped() == this.getMyPhrasesCategoryId() ) {
           this.getPhraseToolbarButton().setText('EDIT');
        }
           
        var els = htmlElement.select('div[class=visible]');
        els.replaceCls('visible', 'hidden');
           
        var el = htmlElement.down('div[class=hidden]');
        el.replaceCls('hidden', 'visible');
        el.show(true); // show with animation
           
        this.playAudio(view,index,htmlElement,e);
    },
    
    // Phrase list view painted
    //
    onPhraseListActivated: function(a, b, c, d) {
        // show toolbar add/edit/done button
        var thisCategory = this.getCategoryTapped();
        
        this.setPhraseTapped(null); //reset currently selected phrase 
        
        if (thisCategory==this.getMyPhrasesCategoryId() ) {
           this.getPhraseToolbarButton().show();
        }
           
        this.filterPhraseSearch();
    },
           
    
    // Toolbar utility button (used for add,edit,done etc)
    //
    onPhraseToolbarButtonTapped: function() {
        console.log('phrase add/edit button tapped');
           
        
        var innerItems = this.getMain().getInnerItems();
        var currentItem = innerItems[innerItems.length-1].xtype; // get current screen/component
        console.log('currentItem=' + currentItem);
        switch(currentItem)
        {
            // if this is the phrase list view 
            case "phrasecontainerlist":
                console.log("add or edit phrase");
            
           //var curRecord = this.getPhraseListView().getStore().getAt( this.getDictionaryDetailView().getCurrentListItem() );
           //var activeIndex = this.getPhraseListView().getInnerItems().indexOf( this.getPhraseListView.getActiveItem() );
                //if ( this.getPhraseListView().getInnerItems().length == 0 ) {
           
                this.getPhraseToolbarButton().setText('DONE');
           
                // if a phrase has been selected in the list then edit
                if ( this.getPhraseTapped() ) {
                    console.log('phrase selected,  must be an edit');
           
                } else
                // no phrase has been selected so add op'
                {
                    console.log('must be an add');
                    this.showForm();
                }
                break;
           /*
            // if this is the dictionary detail view then edit entry
            case "dictionarytargetdetailview":
                console.log("edit dict entry");
                this.getDictionaryEntryButton().setText('DONE');
                this.editForm();
                break;
           
            case "dicmetadataformview":
            	//saving data on metadata form
            	
            	this.setCurrentDate(this.getDicMetadaForm().getComponent('dateField').getValue());
            	this.setCurrentLatitude(this.getDicMetadaForm().getComponent('latitudeField').getValue());
            	this.setCurrentLongitude(this.getDicMetadaForm().getComponent('longitudeField').getValue());
            	this.setRecordingDevice(this.getDicMetadaForm().getComponent('recordingDeviceField').getValue());            	
            	
            	this.getDictionaryEntryButton().setText('DONE');
            	this.getMain().pop();
            	
                	
            	
            	break;
            	
            case "speakerformview":

            	this.setSpeakerName(this.getSpeakerNameField().getComponent('speakerNameField').getValue());
            	
            	this.setSpeakerDOB(this.getSpeakerNameField().getComponent('speakerDOBField').getFormattedValue());
            	    	
            	this.setSpeakerGender(this.getSpeakerGenderField().getGroupValue());
        	
            	this.setSpeakerComment(this.getSpeakerCommentField().getComponent('speakerCommentField').getValue());
            
            	this.getMain().pop();
            	break;
            	
            case "collectorformview":
            	this.setCollectorName(this.getCollectorNameField().getComponent('collectorNameField').getValue());
            	
            	this.setCollectorDOB(this.getCollectorNameField().getComponent('collectorDOBField').getFormattedValue());
            	
            	this.setCollectorGender(this.getCollectorGenderField().getGroupValue());
            	
            	this.setCollectorComment(this.getCollectorCommentField().getComponent('collectorCommentField').getValue());
            	            	
            	this.getMain().pop();
            	
            	break;
            */
            // if this is the dictionary detail view then edit entry
            case "phraseformview":
                var previousItem = innerItems[innerItems.length-2].xtype;
                
                // if add dictionary entry
                //if (previousItem=="dictionarycontainerlist") {
                if ( !this.getPhraseTapped() ) {
                    // Save new entry
                    console.log("save new dict entry");
           
                    // Save and exit
                    this.saveForm();
                    this.filterPhraseSearch();
                    this.getPhraseToolbarButton().setText('+');
                    this.getMain().pop();
                } 
                // if edit dictionary entry
                else {
                    // Save existing entry
                    console.log("save existing dict entry");
                    /*
                    this.getDictionaryEntryButton().setText('EDIT');
                    // call fn to save existing entry
                    // ...
                    
                    this.updateForm();
                    
                    this.getMain().pop();
                    */
                }
                break;
            
           
        }
    },
    
     
     
    //fired when back button is pressed on phrase book 
    //
    onBackButton: function(){
        var innerItems = this.getMain().getInnerItems();
        var currentItem = innerItems[innerItems.length-2].xtype; // get screen/component going to
		
        // This code when using string comparison slows the back buttons respone time by about a second!!!
        // Not usre this will work once we start using the other tabs ie. onBackButton will capture
        // all back button events probably?
        console.log(currentItem);
        switch(currentItem)
        {
            // if the the list view
            case "phraseparentcategorylistview":
                console.log('case phraselistview');
                this.getPhraseToolbarButton().hide();
                this.getPhraseToolbarButton().setText('+');
                //this.getDictionaryEntryButton().setIcon('images/engDictButton@2x.png');
                break;
           
            // if the detail view
            case "phrasecontainerlist":
                console.log('case phrasecontainerlist');
                //  this.getDictionaryEntryButton().setIcon('');
                //this.getDictionaryEntryButton().show();
                this.getPhraseToolbarButton().setText('+');
                break;
           /*
            // ...
            case "dictionaryformview":
            	this.getDictionaryEntryButton().setText('DONE');
                break;
            // if the image view close up
            case "imageview":
                console.log('case imageview');
                //this.getMain().getLayout().setAnimation('slide');
                break;
            */
        }
    },
    
           
    //play audio when list item is selected
    //
    playAudio: function(theDataView, index, target, record) {
        console.log("PLAY audio");
        
        // Get associated DictionaryTarget record using dictionaryTargetId foreign key
        //var associatedRecord = Ext.getStore("DictionaryTargets").getById( record.get('dictionaryTargetId') );
        var audioURL = Sencha.app.getPersistentFileStoreVar() + "/assets/" + record.get('audioURL');
           
        if ( record.get('audioURL') ) {
            // Play the audio file at url
            var my_media = new Media(
                audioURL,
                // success callback
                function() {
                    console.log("pplayAudio():Audio Success");
                
                },
                // error callback
                function(err) {
                    console.log("pplayAudio():Audio Error: "+err);
                    navigator.notification.alert(msg, null, 'Capture error');
                }
            );
           
            Sencha.app.mediaPtr=my_media;
            my_media.release();  
            Sencha.app.mediaPtr.play();
        }
    },
    
    
    // Clear dictionary search - fired when clear button pressed
    // 
    clearPhraseSearchFilter: function() {
        this.getPhraseSearchField().setValue('');
        this.filterPhraseSearch();
    },
    
    
    // Filter dictionary - fired when value has changed on dictionarySearchField
    // 
    filterPhraseSearch: function() {
        console.log('in filterPhraseSearch');
        
        //var sto = this.getDictionarySourceListView().getStore();
        var sto = Ext.getStore('PhrasesFiltered');
        var thisCategory = this.getCategoryTapped();
        var searchString = this.getPhraseSearchField().getValue().toLowerCase();
        console.log('in filter, thisCategory = ' + thisCategory);
        //var doEnglishSearch = this.getEngPhraseButtonOn();
        //var doIwaidjaSearch = this.getIwaPhraseButtonOn();
        
        console.log('searchString = ' + searchString);
         
        var resultsArray=new Array();
        var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
        //var filteredStore = this.getDictionarySourceListView()
        
        /*
        if (searchString=='') {
           Ext.getStore('PhrasesFiltered').setData(resultsArray);
           return;
        }
        */
           console.log('searchString = ' + searchString + ' thisCaregoryt=' + thisCategory );
           
        //console.log('phraseCategoriesListView category tapped=' + this.getPhraseCategoriesListView().getCategoryTapped() );
           
        // Define select statement
        /*
        var whereClause = "";
        if ( doEnglishSearch ) {
           whereClause = "sourcePhrase LIKE '" + searchString + "%'";
           if ( doIwaidjaSearch ) {
                whereClause = whereClause + " OR ";
           }
        } 
        if ( doIwaidjaSearch ) {
           whereClause = whereClause + "targetPhrase LIKE '" + searchString + "%'";
        }
        */
           
        whereClause = "sourcePhrase LIKE '" + searchString + "%'";
           
        
           //console.log("SELECT * FROM PHRASE WHERE categoryId='" + thisCategory + " ORDER BY sourcePhrase COLLATE NOCASE");

        //var whereClause = "sourcePhrase LIKE '" + searchString + "%' ";
          // console.log('select = ' + "SELECT * FROM PHRASE WHERE categoryId='" + thisCategory + "' AND " + whereClause + "ORDER BY sourcePhrase COLLATE NOCASE" );
           
        db.transaction(
            function(tx) {
                tx.executeSql(
                    "SELECT * FROM PHRASE WHERE categoryId='" + thisCategory + "' AND " + whereClause + " ORDER BY sourcePhrase COLLATE NOCASE", 
                    [], 
                    function (tx2, results) {
                        // the number of rows returned by the select statement
                        console.log("NUM ROWS FOUND = " + results.rows.length);
                        
                        var len = results.rows.length;
                        if (len > 50) {
                              len=50;
                        }
                        
                        for (var i=0; i<len; i++){
                              resultsArray[i]=results.rows.item(i);
                        }
                        console.log('packed array. items = ' + i);
                        Ext.getStore('PhrasesFiltered').setData(resultsArray);
                    }, 
                    function (err) {
                        alert("Error processing SQL 2: "+err.code);    
                    }
                );
            },
            function(err) {
                alert("Error processing SQL 1: "+err.code);
            }
        );
    },     
    
    /*
    // Toggle English search on/off
    // mdm 22.04.2012
    //
    toggleEngPhraseButton: function() {
        // if boolean var for button state is true
        if ( this.getEngPhraseButtonOn() ) {
            // only toggle off if the other toggle is on ie. can't have both off
            if ( this.getIwaPhraseButtonOn() ) {
                // toggle button OFF
                this.setEngPhraseButtonOn(false);
                this.getEngPhraseButton().addCls('toggleButtonOff');
                // Refilter list now
                this.filterPhraseSearch();
            }
        } else {
            // toggle button ON
            this.setEngPhraseButtonOn(true);
            // change class
            this.getEngPhraseButton().removeCls('toggleButtonOff');
            // Refilter list now
            this.filterPhraseSearch();
        }
    },
    
    // Toggle Iwaidja search on/off
    // mdm 22.04.2012
    //
    toggleIwaPhraseButton: function() {
        // if boolean var for button state is true
        if ( this.getIwaPhraseButtonOn() ) {
            // only toggle off if the other toggle is on ie. can't have both off
            if ( this.getEngPhraseButtonOn() ) {
                // toggle button OFF
                this.setIwaPhraseButtonOn(false);
                this.getIwaPhraseButton().addCls('toggleButtonOff');
                // Refilter list now
                this.filterPhraseSearch();

            }
        } else {
            // toggle button ON
            this.setIwaPhraseButtonOn(true);
            // change class
            this.getIwaPhraseButton().removeCls('toggleButtonOff');
            // Refilter list now
            this.filterPhraseSearch();

        }
    }
    */
    
    //show add form for phrase
    //
    showForm : function(){
           console.log('in showForm');
        // clear it
        this.setSourcePhrasefield("");
        this.setTargetPhraseField("");
        this.setOrthographyField("");
        this.setNoteField("");
           console.log('after set fields');
        //metadata form
        //Getting the current date, time
        var d = new Date();
        this.setCurrentDate( d.getTime() );
        
        // Set location
        var thisPtr = this;
        navigator.geolocation.getCurrentPosition(
            // Success callback
            function(position) {
                thisPtr.setCurrentLatitude( position.coords.latitude );
                thisPtr.setCurrentLongitude( position.coords.longitude ); 
            }, 
            // Error callback
            function(error) {
                console.log('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
                thisPtr.setCurrentLatitude('');
                thisPtr.setCurrentLongitude('');
            }
        );
           
        this.setRecordingDevice( device.name );
           
        //speaker form
        this.setSpeakerName("");
        this.setSpeakerDOB("");
        this.setSpeakerGender("");
        this.setSpeakerComment("");
           
        //collector form
        this.setCollectorName("");
        this.setCollectorDOB("");
        this.setCollectorGender("");
        this.setCollectorComment("");
           
        this.getMain().push({
            xtype: 'phraseformview'			                    
        });
          
        // We're adding a new entry, so no need for delete button
        this.getPhraseDeleteButton().hide();
    },
     
           
    // Display meta data form
    //
    showMetadataForm: function(){
        this.getPhraseToolbarButton().setText('OK');
           
        this.getMain().push({
            xtype: 'dicmetadataformview'			                    
        });
           
        var d = new Date();
        d.setTime( this.getCurrentDate() );
        this.getDicMetadaForm().getComponent('dateField').setValue( d.toDateString() );
        this.getDicMetadaForm().getComponent('latitudeField').setValue(this.getCurrentLatitude());
        this.getDicMetadaForm().getComponent('longitudeField').setValue(this.getCurrentLongitude());
        this.getDicMetadaForm().getComponent('recordingDeviceField').setValue(this.getRecordingDevice());
    },
    
    // Save form
    //
    saveForm : function(){
        console.log('in saveForm()');
        var currentObj = this;
        var catId = this.getMyPhrasesCategoryId();
           
        this.setSourcePhrasefield( this.getPhraseForm().getComponent('sourcePhraseField').getValue() );
        this.setTargetPhraseField( this.getPhraseForm().getComponent('targetPhraseField').getValue() );
        this.setOrthographyField( this.getPhraseForm().getComponent('orthographyField').getValue() );
        this.setNoteField( this.getPhraseForm().getComponent('noteField').getValue() );
           
        var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
        db.transaction(
            function(tx) {
                var querySpeaker = 'INSERT INTO SPEAKER (id, name, birthDate, gender, comments) VALUES (null, "'+ currentObj.getSpeakerName()+'", "'+currentObj.getSpeakerDOB()+'", "'+currentObj.getSpeakerGender()+'","'+currentObj.getSpeakerComment()+'")';
                          tx.executeSql(querySpeaker);
                          
                var queryCollector = 'INSERT INTO COLLECTOR (id, name, birthDate, gender, comments) VALUES (null, "'+ currentObj.getCollectorName()+'", "'+ currentObj.getCollectorDOB()+'", "'+currentObj.getCollectorGender()+'", "'+currentObj.getCollectorComment()+'")';
                          tx.executeSql(queryCollector);
                          
                console.log('just before select * from speaker...');
                //query the speaker id
                tx.executeSql(
                    'SELECT * FROM SPEAKER', 
                    [], 
                    function(tx,results){
                        currentObj.setSpeakerId(results.rows.length);
                        var phraseSpeakerId = currentObj.getSpeakerId();
                        tx.executeSql(
                            'SELECT * FROM COLLECTOR', 
                            [], 
                            function(tx,results){
                                //query the collector id
                                console.log('query the collector id...');
                                currentObj.setCollectorId(results.rows.length);
                            
                                var phraseCollectorId = currentObj.getCollectorId();
                                
                                console.log('before queryDictionaryTarget');
                                queryPhrase = 'INSERT INTO PHRASE (id, speakerId, collectorId, categoryId, sourcePhrase, targetPhrase, orthography, audioURL, notes, savedDate, latitude, longitude, recordingDevice) VALUES(null, ' + phraseSpeakerId + ', ' + phraseCollectorId + ', "' + catId + '", "' + currentObj.getSourcePhrasefield() + '", "' + currentObj.getTargetPhraseField() + '", "' + currentObj.getOrthographyField() + '", "' + currentObj.getAudioUrlField() + '", "' + currentObj.getNoteField() + '", "' + currentObj.getCurrentDate() + '", "' + currentObj.getCurrentLatitude() + '", "' + currentObj.getCurrentLongitude() + '", "' + currentObj.getRecordingDevice() +'")';
                                console.log('after queryDictionaryTarget. SQL =' + queryPhrase);
                                                      
                                tx.executeSql(queryPhrase);
                            },
                            function() {
                                console.log('sql error callback');
                            }
                        );
                    },
                    function() {
                        console.log('sql error callback 2');
                    }    
                );
            }, 
            errorCB
        );
           
        this.getPhraseListView().getStore().load();
        //Ext.getStore("DictionaryTargets").load();
        Ext.getStore("Collectors").load();
        Ext.getStore("Speakers").load();
    },
           
           
    // Delete dictionary entry
    //
    deletePhraseEntry : function(){
        console.log('deletephrase entry');
           /*
           var dictionarySourceStore = Ext.getStore("DictionarySources");
           var dictionaryTargetStore = Ext.getStore("DictionaryTargets");
           var speakerStore = Ext.getStore("Speakers");
           var collectorStore = Ext.getStore("Collectors");
           
           var sourceModel = dictionarySourceStore.getById(this.getDictionaryForm().getComponent('sourceIdField').getValue());
           
           dictionarySourceStore.remove(sourceModel);
           dictionarySourceStore.sync();
           
           var dicTargetId = this.getDictionaryForm().getComponent('targetIdField').getValue();
           
           if( dictionarySourceStore.find("dictionaryTargetId", dicTargetId) == -1){
           var targetModel = dictionaryTargetStore.getById(dicTargetId);
           
           dictionaryTargetStore.remove(targetModel);
           dictionaryTargetStore.sync();
           
           var dicSpeakerId = this.getDictionaryForm().getComponent('speakerIdField').getValue();
           var dicCollectorId = this.getDictionaryForm().getComponent('collectorIdField').getValue();
           
           if(dictionaryTargetStore.find("speakerId", dicSpeakerId) == -1){
           var speakerModel = speakerStore.getById(dicSpeakerId);
           
           speakerStore.remove(speakerModel);
           speakerStore.sync();
           }
           
           if(dictionaryTargetStore.find("collectorId", dicCollectorId) == -1){
           var collectorModel = collectorStore.getById(dicCollectorId);
           
           collectorStore.remove(collectorModel);
           collectorStore.sync();
           }
           
           }
           
           this.getDictionaryEntryButton().setText('+');
           this.getMain().pop(2);
           //this.getMain().pop();
           //this.getMain().pop();	
            */
    }
           
    
});
